package ferp.center.server.ranking;

import ferp.center.server.entity.Range;
import ferp.center.server.entity.RangeTree;
import ferp.center.server.entity.Rating;

import javax.persistence.EntityManager;

/**
 * User: igorgok
 * Date: 6/3/13 4:27 PM
 */
class Create
{
  static RangeTree tree(EntityManager em, String configuration)
  {
    RangeTree tree = new RangeTree(configuration);
    Range root = Range.root();

    // write root
    em.persist(root);
    em.refresh(root);

    tree.setRoot(root);

    // write tree
    em.persist(tree);
    em.refresh(tree);

    return tree;
  }

  static Range root(EntityManager em, RangeTree tree, Range target, Range sibling)
  {
    // add the new tree root
    Range root = Range.root(target, sibling);

    // make sure we have the key for the new range
    // todo: remove this logic
    em.persist(root);
    em.refresh(root);

    target.setParent(root);
    sibling.setParent(root);
    tree.setRoot(root);

    return root;
  }

  static Range leaf(EntityManager em, Rating rating)
  {
    Range leaf = Range.leaf(rating);

    em.persist(leaf);
    em.refresh(leaf);

    return leaf;
  }
}
